// 引入 用来发送请求的方法
import {request} from "../../request/index.js";
var util = require("../../utils/util");

// pages/commodity/commodity.js
Page({
  data: {
    placeholder: '还没有人留言哦～',
    commonHolder: '我要留言...',
    commodity:null,
    swiperList:[],
    // 当前用户 Id
    currentUserId:0,
    // 收藏图标显示
    collectState:false,
    // 点赞状态
    praiseState: false,
    // 用户与商品最初的收藏状态
    startCollectState:null,
    // 举报表单弹出框
    showModal:false,
    // 点赞状态
    supportState: false,
    startSupportState: null,
    // 键盘高度
    keyboardHeight: 0,
    // 是否为苹果手机
    isIOS: false,
    //头像
    avatarUrl: '',
    // 输入的评论内容
    message: '',
    // 查询评论每页大小
    limit: 10,
    // 查询评论当前页
    currentPage: 1,
    // 评论数据
    commentList: [],
    // 要回复的评论
    replyComm: null
  
  },

// 获取具体商品信息
  getCommodityDetail(id){
    request({url:util.BASE_URL + "commodity/commodityDetail/" + id})
    .then(result => {
      this.setData({
        commodity:result.data,
        swiperList:result.data.commodityImgList
      })
    });
  },

  // 查询评论信息
  queryCommentForCommodity(id){
    let that = this;
    let {limit, currentPage, commentList} = this.data;
    
    wx.request({
      url: `${util.BASE_URL}commComment/list`,
      method: 'GET',
      data: {
        limit,
        page: currentPage,
        cId: id
      },
      success({data}){
         let {records} = data.data;
         if(records && records.length > 0){
           commentList.push(...records);
           that.setData({commentList});
         }
      }
    })
  },


  // 预览轮播图
  handlePerviewImg:function(e){
    let swiperImgList = [];
    let index = e.currentTarget.dataset.index;
    let swiperList = this.data.swiperList;
    for(let i = 0 ; i < swiperList.length;i++){

      swiperImgList.push(swiperList[i].imgSrc);
    }
    wx.previewImage({
      urls: swiperImgList,
      current:swiperImgList[index]
    })
  },
  // 显示提示信息
  showMessage(options){
    let that = this;
    wx.showToast({
      title: '功能开发中敬请期待',
      icon:'none',
      duration: 1500
    })
  },
  // 修改商品浏览量，关闭页面时，浏览量 +1
  updateClickCount:function(){
    let id = this.data.commodity.id;
    request({url:util.BASE_URL + "commodity/updateClickCount/" + id})
    .then();
  },
  // 获取收藏的最初始状态
  startCollectState:function(commodityId,userId){
    let that = this;
    wx.request({
      url: util.BASE_URL +  'user/startCollectState',
      method: 'GET',
      data:{
        commodityId,
        userId
      },
      success:function(res){
        if(res.data.success == true){
          that.setData({
            startCollectState:true,
            collectState:true
          });
        } else{
          that.setData({
            startCollectState:false
          });
        }
      }
    })
  },

  // 获取收藏的最初始状态
  startSupportState:function(cId,uId){
    let that = this;
    wx.request({
      url: util.BASE_URL +  'support/query',
      method: 'GET',
      data:{
        cId,uId
      },
      success:function({data}){
        console.log("点赞结果", data);
        if(data.data == true){
          that.setData({
            startSupportState:true,
            supportState:true
          });
        } else{
          that.setData({
            startSupportState:false
          });
        }
      }
    })
  },

  // 点赞按钮，点击事件
  handleUpdateSupport: function(){
      // 当前用户 id
      let userId = wx.getStorageSync('userInfo').id;
      if(userId == undefined){
        util.warning("请先登录");
        wx.navigateTo({
          url: '../login/login',
        })
        return;
      } 
      let supportState = this.data.supportState;
      if(supportState){
        this.setData({
          supportState:false
        });
        util.warning("取消点赞");
      } else{
        this.setData({
          supportState:true
        });
        util.warning("已点赞");
      }
  },

  // 收藏按钮，点击事件。不会产生实质的效果，退出页面后才进行收藏/取消收藏
  handleUpdateCollect:function(){
    // 当前用户 id
    let userId = wx.getStorageSync('userInfo').id;
    if(userId == undefined){
      util.warning("请先登录");
      wx.navigateTo({
        url: '../login/login',
      })
      return;
    } 
    let collectState = this.data.collectState;
    if(collectState){
      this.setData({
        collectState:false
      });
      util.warning("取消收藏");
    } else{
      this.setData({
        collectState:true
      });
      util.warning("已收藏");
    }
  },
  // 添加收藏
  addCollect:function(commodityId,userId){
    wx.request({
      url: util.BASE_URL +  'user/addCollect',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      }, 
      data:{
        commodityId,
        userId
      },
      success:function(res){
      console.log(res);
      }
    })
  },
  // 取消（删除）收藏
  deleteCollect:function(commodityId,userId){
    wx.request({
      url: util.BASE_URL +  'user/cancelCollect',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      }, 
      data:{
        commodityId,
        userId
      },
      success:function(res){
  console.log(res);
      }
    })
  },

  // 点击或取消点赞
  addOrDelSupport(commodityId, userId){
    let {supportState} = this.data;
    let url = supportState? '/add': '/del';
    wx.request({
      url: `${util.BASE_URL}support${url}`,
      method: supportState? 'POST': 'DELETE',
      data: {
        commodityId, userId
      }
    })
  },

  // 跳转到用户店铺（前提是先登录）
  handleToUserStore:function(e){
    let userId = wx.getStorageSync('userInfo').id || '0';
    if(userId == undefined){
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration:2000
      })
    } else{
      let url = e.currentTarget.dataset.url;
      wx.navigateTo({
        url: url
      })
    }
  },
// 打开举报表单弹出层
  handleShowModal:function(){
    // 当前用户Id
    let userId = wx.getStorageSync('userInfo').id;
    if(userId != undefined){
      this.setData({
        showModal:true
      });
    } else{
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      })
    }
  },
// 关闭举报表单弹出层
  handleCloseModal:function(){
    this.setData({
      showModal:false
    });
  },

  // 发送举报信息
  handleSubmitInform:function(e){
    let that = this;
    let content = e.detail.value.informText;
    if(content == ''){
      wx.showToast({
        title: '举报内容不能为空',
        icon: 'none',
        duration: 2000
      }) 
    } else{
      // 举报人
      let userId = wx.getStorageSync('userInfo').id;
      // 举报的商品
      let commodityId = this.data.commodity.id;
      wx.request({
        url: util.BASE_URL +  'inform/commodityInform',
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        }, 
        data:{
          userId,
          commodityId,
          content
        },
        success:function(res){
        console.log(res);
          if(res.data.success == true){
          console.log(res.data);
            that.handleCloseModal();
            wx.showToast({
              title: '已发送，待审核',
              icon: 'none',
              duration:2000
            })
          } else{
            wx.showToast({
              title: '发送失败',
              icon: 'none',
              duration:2000
            })
          }
        },
        fail:function(err){
          wx.showToast({
            title: '网络错误',
            icon: 'none',
            duration: 2000
          })
        }
      })
    }
  },
  // 复制商品编号
  copySerial:function(e){
    util.copyText(e.currentTarget.dataset.serial);
  },

  // 分享按钮事件
  shareHandle(){
    console.log('点击分享');
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },
  
  // 结缘
  applyBondHandle: function(e){
    const applicant = wx.getStorageSync('userInfo').id;
    const commodity = e.currentTarget.dataset.id;
    request({
      url: util.BASE_URL + `apply/list`,
      method: "GET",
      data: {
        applicant,
        commodity,
      }
    }).then(result => {
       console.log('返回结果', result);
       let list = result.data.data.list;
       if(!list || list.length == 0 ){
          wx.navigateTo({
            url: `../applyBond/applyBond?id=${commodity}`,
          })
       }else{
        wx.showToast({
          title: '请勿重复申请',
          icon: 'none',
        })
       }
     });

     return false;
  },

  // 点击回复评论
  replyCommentHandle(e){
    console.log('回复评论信息', e);
    const currentUserId = wx.getStorageSync('userInfo').id;
    let replyComm = e.currentTarget.dataset.value;
    // 不能给自己回复
    if(currentUserId == replyComm.uid){
      wx.showToast({
        title: '不能回复自己的评论',
        icon: "none",
        duration: 1500,
      }); 
      return;
    }
    this.setData({replyComm});
    this.commentInputTap();
  },

  // 弹出评论输入框输入数据事件
  commentTextAreaInputHandle(event){
    let {value} = event.detail;
    this.setData({message: value.trim()});
  },

  // 点击发送按钮事件
  sendCommentHandle(){
    let that = this;
    let {message, commodity, replyComm} = this.data;
    let userId = wx.getStorageSync('userInfo').id;
    let {nickName, avatarUrl} = wx.getStorageSync('userInfo');
    
    let data = {
      cid: commodity.id,
      avatar: avatarUrl,
      uname: nickName,
      uid: userId,
      context: message,
      replyId: 0
    };
    if(replyComm){
      data['replyId'] = replyComm.id;
      data['replyUid'] = replyComm.uid;
      data['replyUname'] = replyComm.uname;
    }
    wx.request({
      url: `${util.BASE_URL}commComment/add`,
      method: 'POST',
      data,
      success(res){
        console.log("保存留言结果", res);
        if(res.data.success){
          util.success();
          that.setData({currentPage: 1, commentList: []});
          that.queryCommentForCommodity(commodity.id);
        }
      },
      fail(){},
      complete(){
        that.setData({replyComm: null});
      },
    })
  },

  // 点击评论框时，是隐藏的评论输入框获取焦点并显示
  commentInputTap: function(e){
    // 如果是点击的发送评论则情况回复数据
    if(e){
      this.setData({replyComm: null});
    }
    let uId = util.verifyHasLogin();
    if(!uId){
      return;
    }
    this.setData({showComtBox: true});
  },

  // 评论信息输入框获取焦点事件
  ctFocus: function(e){
    let keyboardHeight = e.detail.height;
    console.log("文本框键盘高度", keyboardHeight);
    this.setData({ keyboardHeight})
  },

  // 初始化是绑定键盘事件
  initKeyboardHeight: function(){
    const that = this;
    wx.onKeyboardHeightChange(res => {
        let keyboardHeight = res.height;
        console.log("键盘高度为", keyboardHeight);
        that.setData({showComtBox: keyboardHeight > 0});
    })
  },

  // 点击显示更多回复事件
  showMoreReplyHandle(e){
    let {index} = e.currentTarget.dataset;
    let {commentList} = this.data;
    commentList[index].show = true;
    let chidren = commentList[index].children;
    let temp = [];
    chidren.forEach(function(item, idx){
       item.show = true;
       temp.push(item);
    });
    commentList[index].children = temp;
    this.setData({commentList});
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let id = options.id;
    // 获取商品详情
    this.getCommodityDetail(id);
    this.queryCommentForCommodity(id);
    // 当前用户Id
    let userId = wx.getStorageSync('userInfo').id;
    let avatarUrl = wx.getStorageSync('userInfo').avatarUrl;
    if(userId != undefined){
      this.setData({
        currentUserId:userId,
        avatarUrl
      });
      // 设置收藏最初状态
      this.startCollectState(id,userId);
      this.startSupportState(id, userId);
    }
    this.initKeyboardHeight();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 当前用户
    let userId = wx.getStorageSync('userInfo').id;
    // 商品发布者
    let pubUserId = this.data.commodity.user.id;
    let commodityId = this.data.commodity.id;
    // 加浏览量
    if(userId != pubUserId){
      // 关闭页面时，浏览量 +1
      this.updateClickCount();
    }
    // 没有登录，所有收藏操作隐蔽
    if(userId != undefined){
      // 收藏、取消收藏
      // 收藏状态没变，不进行任何操作
      if(this.data.startCollectState != this.data.collectState){
        let collectState = this.data.collectState;
        if(collectState){
          // 收藏
          this.addCollect(commodityId,userId);
        } else{
          // 取消收藏
          this.deleteCollect(commodityId,userId);
        }
      } 
      if(this.data.supportState != this.data.startSupportState){
        this.addOrDelSupport(commodityId,userId);
      }
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})